import { ref, computed } from 'vue'
import type { PlayerRank, RankingChange, MatchResult } from '../types/ranking'

export function useRankingSystem() {
  const players = ref<PlayerRank[]>([])
  const rankingHistory = ref<Map<string, RankingChange[]>>(new Map())

  // ELO 等级分计算
  const calculateEloChange = (
    winnerRating: number,
    loserRating: number,
    isDraw: boolean = false
  ): number => {
    const K = 32 // K因子，可以根据等级分范围调整
    const expectedScore = 1 / (1 + Math.pow(10, (loserRating - winnerRating) / 400))
    const actualScore = isDraw ? 0.5 : 1
    return Math.round(K * (actualScore - expectedScore))
  }

  // 更新玩家等级分
  const updateRatings = (result: MatchResult) => {
    const winner = players.value.find(p => p.id === result.winner)
    const loser = players.value.find(p => p.id === result.loser)
    
    if (!winner || !loser) return

    const ratingChange = calculateEloChange(
      winner.rating,
      loser.rating,
      result.isDraw
    )

    const winnerChange: RankingChange = {
      oldRating: winner.rating,
      newRating: winner.rating + ratingChange,
      change: ratingChange,
      reason: `Match against ${loser.username}`
    }

    const loserChange: RankingChange = {
      oldRating: loser.rating,
      newRating: loser.rating - ratingChange,
      change: -ratingChange,
      reason: `Match against ${winner.username}`
    }

    // 更新等级分历史
    const winnerHistory = rankingHistory.value.get(winner.id) || []
    const loserHistory = rankingHistory.value.get(loser.id) || []
    
    rankingHistory.value.set(winner.id, [...winnerHistory, winnerChange])
    rankingHistory.value.set(loser.id, [...loserHistory, loserChange])

    // 更新玩家统计
    if (result.isDraw) {
      winner.draws++
      loser.draws++
      winner.winStreak = 0
      loser.winStreak = 0
    } else {
      winner.wins++
      winner.winStreak++
      winner.bestRating = Math.max(winner.bestRating, winner.rating + ratingChange)
      loser.losses++
      loser.winStreak = 0
    }

    winner.rating += ratingChange
    loser.rating = Math.max(100, loser.rating - ratingChange)
    winner.lastActive = loser.lastActive = result.date
  }

  // 获取排行榜
  const leaderboard = computed(() => {
    return [...players.value].sort((a, b) => b.rating - a.rating)
  })

  // 获取玩家排名
  const getPlayerRank = (playerId: string): number => {
    return leaderboard.value.findIndex(p => p.id === playerId) + 1
  }

  // 获取玩家等级分历史
  const getPlayerHistory = (playerId: string): RankingChange[] => {
    return rankingHistory.value.get(playerId) || []
  }

  // 计算胜率
  const getWinRate = (player: PlayerRank): number => {
    const totalGames = player.wins + player.losses + player.draws
    return totalGames > 0 ? (player.wins / totalGames) * 100 : 0
  }

  return {
    players,
    leaderboard,
    updateRatings,
    getPlayerRank,
    getPlayerHistory,
    getWinRate
  }
} 